#include "oewalletmanagewidget.h"

// inc qt
#include <QMessageBox>
#include <QSettings>
#include <QHeaderView>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QTableView>
#include <QStandardItemModel>
#include <QPushButton>
#include <QMenu>
#include <QAction>
#include <QPushButton>
#include <QCheckBox>
#include <QLabel>
#include <QSpinBox>
#include <QDebug>
#include <QGridLayout>
#include <QDir>
#include <QFileDialog>
#include <QDateTime>



#include <quazip/quazipdir.h>
#include <quazip/JlCompress.h>

#define QUAZIP_OPERATOR  // 钱包zip导入导出


// inc my
#include "page/srcreatewalletpage.h"
#include "log/srdatabase.h"
// inc my lib
#include <OEMessageBox>
#include <OEFramelessWindow>
#include <OEWalletManage>

#define WALLET_NAME (0)
#define WALLET_STATUS (1)
#define WALLET_AUTHOR (2)
#define WALLET_TIME (3)
#define WALLET_PATH (4)
#define WALLET_COUNT (5)

OEWalletManageWidget::OEWalletManageWidget(QWidget *parent)
    : QWidget(parent),createWalletPage_(Q_NULLPTR)
{
    resize(888,666);
    walletInfo_ = new OEWalletManage();


    QVBoxLayout* layout = new QVBoxLayout();
    QHBoxLayout* layout_wallet_operation = new QHBoxLayout();
    QHBoxLayout* layout_status = new QHBoxLayout();

    labWalletCount_ = new QLabel("    钱包总数：");
    labWalletCount_->setObjectName("    钱包总数：%1");

    checkNormal_ = new QCheckBox(tr("未分配"));
    checkUse_ = new QCheckBox(tr("使用中"));
    checkBusy_ = new QCheckBox(tr("提币中"));
    checkHide_ = new QCheckBox(tr("隐藏"));

    QPushButton* btn_export_pubkey = new QPushButton(tr("导出公钥"));
    QPushButton* btn_export_wallet = new QPushButton(tr("导出钱包"));
    QPushButton* btn_import_wallet = new QPushButton(tr("导入钱包"));
    QPushButton* btn_hide_wallet = new QPushButton(tr("隐藏钱包"));

    model_ = new QStandardItemModel();
    tableView_ = new QTableView();

    QHeaderView *headerGoods = tableView_->horizontalHeader();
    //SortIndicator为水平标题栏文字旁边的三角指示器
    headerGoods->setSortIndicator(0, Qt::AscendingOrder);
    headerGoods->setSortIndicatorShown(true);
    connect(headerGoods, SIGNAL(sectionClicked(int)),
            tableView_, SLOT (sortByColumn(int)));

    boxPage_ = new QSpinBox();
    boxPage_->setRange(1,99);
    QLabel* lab_page = new QLabel(tr("页数:"));

    // 创建按钮
    QPushButton* btn_create = new QPushButton(tr("创建钱包"));
    QPushButton* btn_select_all = new QPushButton(tr("选择全部"));
    QMenu* menu_create = new QMenu();
    QAction* action_create_wallet = new QAction(tr("密语创建钱包"),this);
    QAction* action_getback_wallet = new QAction(tr("密语恢复钱包"),this);
    QAction* action_import_wallet = new QAction(tr("导入钱包"),this);
    QAction* action_hide_wallet = new QAction(tr("隐藏钱包"),this);
    QAction* action_use_wallet = new QAction(tr("启用钱包"),this);
    QAction* action_export_wallet = new QAction(tr("导出钱包"),this);
    QAction* action_export_pubkey = new QAction(tr("导出公钥"),this);

    action_create_wallet->setShortcut(QKeySequence::New);
    action_import_wallet->setShortcut(QKeySequence::Open);
    menu_create->addAction(action_create_wallet);
    menu_create->addAction(action_getback_wallet);
    menu_create->addAction(action_import_wallet);
    btn_create->setMenu(menu_create);

    /// 属性初始化
    // check box
    checkBusy_->setChecked(true);
    checkUse_->setChecked(true);
    checkNormal_->setChecked(true);
    boxPage_->setValue(1);
    boxPage_->setFixedSize(75,22);


    // model 初始化
    model_->setColumnCount(5);
    model_->setHeaderData(WALLET_NAME, Qt::Horizontal, tr("钱包名"));
    model_->setHeaderData(WALLET_STATUS, Qt::Horizontal, tr("状态"));
    model_->setHeaderData(WALLET_AUTHOR, Qt::Horizontal, tr("创建者"));
    model_->setHeaderData(WALLET_TIME, Qt::Horizontal, tr("创建时间"));
    model_->setHeaderData(WALLET_PATH, Qt::Horizontal, tr("钱包路径"));

    insertTableData(1,"1","1","1","1","1");
    // tableview 初始化
    tableView_->setModel(model_);
    tableView_->setSelectionBehavior(QAbstractItemView::SelectRows); // 选中整行
    tableView_->setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection); // 只能单选
    tableView_->setEditTriggers(QTableView::EditTrigger::NoEditTriggers);
    tableView_->setAlternatingRowColors(true);
    tableView_->setMouseTracking(true);
    // 设置tableview的菜单
    tableView_->setContextMenuPolicy(Qt::ActionsContextMenu);
#ifdef ADMIN_WALLET
    tableView_->addAction(action_export_pubkey);
    tableView_->addAction(action_export_wallet);
#endif
    tableView_->addAction(action_use_wallet);
    tableView_->addAction(action_hide_wallet);


    tableView_->setColumnWidth(0, 160);
    tableView_->setColumnWidth(1, 130);
    tableView_->setColumnWidth(2, 111);
    tableView_->setColumnWidth(3, 130);
    tableView_->horizontalHeader()->setSectionResizeMode(0,QHeaderView::Stretch);
    tableView_->horizontalHeader()->setSectionResizeMode(1,QHeaderView::Fixed);
    tableView_->horizontalHeader()->setSectionResizeMode(2,QHeaderView::Fixed);
    tableView_->horizontalHeader()->setSectionResizeMode(3,QHeaderView::Fixed);
    tableView_->horizontalHeader()->setSectionResizeMode(4,QHeaderView::Stretch);


    /// 大小
    btn_create->setFixedSize(100,30);
    btn_export_pubkey->setFixedSize(100,30);
    btn_export_wallet->setFixedSize(100,30);
    btn_import_wallet->setFixedSize(100,30);
    btn_hide_wallet->setFixedSize(100,30);
    btn_select_all->setFixedSize(100,30);


    /// 布局
#ifdef ADMIN_WALLET /// 董事长版钱包管理
    layout_wallet_operation->addWidget(btn_create, 0, Qt::AlignLeft);
    layout_wallet_operation->addStretch(100);
    layout_wallet_operation->addWidget(btn_select_all, 0, Qt::AlignHCenter);
    layout_wallet_operation->addWidget(btn_export_pubkey, 0, Qt::AlignHCenter);
    layout_wallet_operation->addWidget(btn_export_wallet, 0, Qt::AlignHCenter);
    layout_wallet_operation->addWidget(btn_hide_wallet, 0, Qt::AlignHCenter);
    layout_wallet_operation->addStretch(100);
    layout_wallet_operation->addWidget(checkNormal_, 20, Qt::AlignRight);
    layout_wallet_operation->addWidget(checkUse_, 0, Qt::AlignRight);
    btn_import_wallet->hide();
#else
    btn_create->hide();
    btn_export_pubkey->hide();
    btn_export_wallet->hide();
    layout_wallet_operation->addWidget(btn_select_all, 0, Qt::AlignHCenter);
    layout_wallet_operation->addWidget(btn_import_wallet, 0, Qt::AlignLeft);
    layout_wallet_operation->addWidget(btn_hide_wallet, 0, Qt::AlignLeft);
    layout_wallet_operation->addStretch(100);
    checkNormal_->hide();
    checkUse_->hide();
#endif
    layout_wallet_operation->addWidget(checkBusy_, 0, Qt::AlignRight);
    layout_wallet_operation->addWidget(checkHide_, 0, Qt::AlignRight);

    layout_status->addStrut(35);
    layout_status->addWidget(labWalletCount_,0, Qt::AlignLeft);
    layout_status->addSpacing(50);
    layout_status->addWidget(lab_page, 0, Qt::AlignLeft);
    layout_status->addWidget(boxPage_, 0, Qt::AlignLeft);
    layout_status->addStretch(999);
    layout->addLayout(layout_wallet_operation);
    layout->addWidget(tableView_);
    layout->addLayout(layout_status);

    setLayout(layout);

    /// link
    // action
    connect(action_use_wallet, &QAction::triggered,
            this, [=]{

        int ret_row = tableView_->currentIndex().row();
        if (-1 == ret_row) {
            OEMessageBox::BriefMessage(this, tr("请选择要启用的钱包"));
            return;
        }

        QString wallet_path = model_->item(ret_row, WALLET_PATH)->text();
        QString wallet_config = wallet_path + "/wallet";

        QSettings setting(wallet_config,QSettings::IniFormat);
        setting.setValue("INFO/status", "提币中");
        this->onUpdate();
    });
    connect(action_create_wallet, &QAction::triggered,
            this, &OEWalletManageWidget::onCreateWalletFromCryptolalia);
    connect(action_getback_wallet, &QAction::triggered,
            this, &OEWalletManageWidget::onGetbackWalletFromCryptolalia);
    connect(action_import_wallet, &QAction::triggered,
            this, &OEWalletManageWidget::onGetbackWalletFromFile);
    connect(action_export_wallet, &QAction::triggered,
            this, [=]{
        this->onExportWallet();
    });
    connect(walletInfo_, &OEWalletManage::sigLoaded,
            this, [=]{
        btn_select_all->setText(tr("选择全部"));
    });
    connect(action_export_pubkey, &QAction::triggered,
            this, [=]{
        this->onExportPubKey();
    });
    connect(btn_select_all, &QPushButton::clicked,
            this, [=]{
        Qt::CheckState state = Qt::Checked;
        if (!btn_select_all->text().compare("选择全部")) {
            state = Qt::Checked;
            btn_select_all->setText(tr("取消全部选择"));
        }
        else {
            state = Qt::Unchecked;
            btn_select_all->setText(tr("选择全部"));
        }

        for (int r = 0, row_count = this->model_->rowCount();
             r < row_count; ++r)
            this->model_->item(r,0)->setCheckState(state);

    });
    connect(action_hide_wallet, &QAction::triggered,
            this, [=]{
        this->onHideWallet();
    });

    // box
    connect(boxPage_, SIGNAL(valueChanged(int)),
            this, SLOT(onNextPage(int)));

    connect(tableView_,&QTableView::clicked,
            this, &OEWalletManageWidget::onTableClick);

    // checkbox
    connect(checkNormal_, &QCheckBox::clicked,
            this, &OEWalletManageWidget::onUpdate);
    connect(checkBusy_, &QCheckBox::clicked,
            this, &OEWalletManageWidget::onUpdate);
    connect(checkHide_, &QCheckBox::clicked,
            this, &OEWalletManageWidget::onUpdate);
    connect(checkUse_, &QCheckBox::clicked,
            this, &OEWalletManageWidget::onUpdate);

    // button
    connect(btn_export_pubkey, &QPushButton::clicked,
            this, &OEWalletManageWidget::onBatchExportPubKey);
    connect(btn_export_wallet, &QPushButton::clicked,
            this, &OEWalletManageWidget::onBatchExportWallet);
    connect(btn_hide_wallet, &QPushButton::clicked,
            this, &OEWalletManageWidget::onBatchHideWallet);
    connect(btn_import_wallet, &QPushButton::clicked,
            this, &OEWalletManageWidget::onGetbackWalletFromFile);
}

void OEWalletManageWidget::onCreateWalletFromCryptolalia()
{
    if (createWalletPage_) {
        createWalletPage_->deleteLater();
        createWalletPage_ = Q_NULLPTR;
    }

    createWalletPage_ = new SRCreateWalletPage(0);
    connect(createWalletPage_, &SRCreateWalletPage::sigClose,
            this, [=]{
        createWalletPage_->deleteLater();
        createWalletPage_ = Q_NULLPTR;
        onUpdate();
    });
    createWalletPage_->show();
    createWalletPage_->raise();

}

void OEWalletManageWidget::onGetbackWalletFromCryptolalia()
{
    if (createWalletPage_) {
        createWalletPage_->deleteLater();
        createWalletPage_ = Q_NULLPTR;
    }
    createWalletPage_ = new SRCreateWalletPage(1);
    connect(createWalletPage_, &SRCreateWalletPage::sigClose,
            this, [=]{
        createWalletPage_->deleteLater();
        createWalletPage_ = Q_NULLPTR;
        onUpdate();
    });
    createWalletPage_->show();
    createWalletPage_->raise();
}
void OEWalletManageWidget::onGetbackWalletFromFile()
{
    QString file_path = QFileDialog::getOpenFileName(this,
                                        tr("请选择文件夹钱包"),"..", "Bepal Wallets(*.wallet);;Zip Files (*zip)");
    if (file_path.isEmpty())
        return;


#if 1  // 检验当前操作是否试图导入钱包目录下的钱包
    QString crt_path = QDir::currentPath();
    QStringList list = file_path.split(crt_path);

    if (list.size() >= 2) {
#ifdef OEASYMESSAGE_H
//        manager->notify("还原失败",tr("不可还原根钱包下的钱包"),":/ico/logo","");
        OEMessageBox::BriefMessage(this, tr("不可还原根钱包下的钱包"));
#else
        qDebug() << "不可还原根钱包下的钱包";
#endif
        return;
    }
#endif





#ifdef QUAZIP_OPERATOR /// 读取压缩钱包
    QuaZip zip(file_path);
    zip.open(QuaZip::mdUnzip);
    if (!zip.isOpen()) {
        qDebug() << file_path;
        OEMessageBox::BriefMessage(this, tr("读取钱包失败"));
        return;
    }
    QStringList list_name = zip.getFileNameList();
    int ret = list_name.indexOf("wallet");
    if (ret == -1) {
        OEMessageBox::BriefMessage(this, tr("请选择正确的钱包"));
        return;
    }
    zip.close();

    QDir(".").remove("temp/zip/wallet");
    QDir(".").mkpath("temp/zip");
    QString wallet_config = "temp/zip/wallet";

    JlCompress::extractDir(file_path,"temp/zip/");

#else
    QString wallet_config = file_path + "/wallet";
    if (!QFileInfo(wallet_config).exists() || !QFileInfo(wallet_config).isFile())
    {
#ifdef OEASYMESSAGE_H
//        manager->notify("还原失败",tr("请选择正确的钱包文件夹"),":/ico/logo","");
      OEMessageBox::BriefMessage(this, tr("请选择正确的钱包文件夹"));
#else
        qDebug() << "请选择正确的钱包文件夹";
#endif
    }
#endif


#if 1 // 判断钱包是否存在

    QSettings setting(wallet_config,QSettings::IniFormat);
//    qDebug() << setting.value("INFO/status").toString();
    QString ek_pub_key = setting.value("INFO/ek_pub_key").toString();

    auto wallet = walletInfo_->getWalletInfo(ek_pub_key);
    QString dest_file_path = QDateTime::currentDateTime().toString("MMddzzz_HHmmss_yyyy");
    if(!wallet.name.isEmpty()) {
        // 提示
        int ret = QMessageBox::question(this, "钱包已存在", "是否覆盖本地钱包",
                                        QMessageBox::Yes|QMessageBox::No);
        if (ret != QMessageBox::Yes)
            return;

        dest_file_path = wallet.absPath;
    }
#endif


    QDir(QDir::currentPath()).mkdir(dest_file_path);
#ifdef QUAZIP_OPERATOR
    JlCompress::extractDir(file_path,dest_file_path);
//    dest_file_path += "wallet";
//    QSettings config(dest_file_path,QSettings::IniFormat);
//    config.setValue("INFO/status", "提币中");
#else
    copyDir(file_path, dest_file_path, true);
#endif

    // 添加记录
    const QString& wallet_name = setting.value("INFO/name").toString();

    SRDatabase::DB()->writeOperateLog(QString("成功导入 钱包(%1) 到 %2")
             .arg(wallet_name).arg(dest_file_path), 1);


    onUpdate();
}

void OEWalletManageWidget::onBatchExportWallet()
{
    if (!isSelectedTable()) {
        OEMessageBox::BriefMessage(this, "请选择钱包");
        return;
    }
    const QString& dest_file_path = QFileDialog::getExistingDirectory(this,
                      tr("请选择钱包导出路径"),"..");

    if (dest_file_path.isEmpty())
        return;

    const int& ROW = model_->rowCount();
    int export_count = 0;
    for (int row = 0; row < ROW; ++row) {
        if (model_->item(row)->checkState() == Qt::Checked) {
            onExportWallet(row,dest_file_path);
            ++export_count;
        }
    }

    SRDatabase::DB()->writeOperateLog(QString("批量导出 %1 个钱包到 %2")
             .arg(export_count).arg(dest_file_path), 1);
    onUpdate();
}

void OEWalletManageWidget::onExportWallet(int _row,
                           const QString& _exportAddr)
{
    int select_row = tableView_->currentIndex().row();

    if (_row != -1) {
        select_row = _row;
    }
    if (-1 == select_row) {
        OEMessageBox::BriefMessage(this, tr("请选择要导出的钱包"));
        return;
    }


    QString dest_file_path = _exportAddr;
    if (dest_file_path.isEmpty()) {
        dest_file_path = QFileDialog::getExistingDirectory(this,
                      tr("请选择钱包导出路径"),"..");
    }

    if (dest_file_path.isEmpty())
        return;

#if 1 // 检验导出路径是否合法
    QString crt_path = QDir::currentPath();
    QStringList list = dest_file_path.split(crt_path);

    if (list.size() >= 2) {
#ifdef OEASYMESSAGE_H
//        manager->notify("导出失败",tr("不可导出到钱包根目录"),":/ico/logo","");
        OEMessageBox::BriefMessage(this, tr("不可导出到钱包根目录"));
#else
        qDebug() << "不可导出到钱包根目录";
#endif
        return;
    }
#endif


    const QString& wallet_root_path = model_->item(select_row, WALLET_PATH)->text();
    const QString& wallet_config = wallet_root_path + "/wallet";
    QSettings setting(wallet_config,QSettings::IniFormat);
    setting.setValue("INFO/status", "提币中");
    const QString& wallet_name = setting.value("INFO/name").toString();
//    qDebug() << setting.value("INFO/status").toString();

    // 拼接导出的钱包路径

    // 生成钱包路径
    QDir("").mkpath(dest_file_path);

    dest_file_path = dest_file_path + "/" + wallet_name
            + QDateTime::currentDateTime().toString("yyyyMMddhhmmsszzz");

    /// 开始导出钱包
#ifdef QUAZIP_OPERATOR
    dest_file_path += ".wallet";
    JlCompress::compressDir(dest_file_path,wallet_root_path);
#else
    copyDir(wallet_root_path, dest_file_path, true);
#endif

    if (_row == -1) {
        onUpdate();
        SRDatabase::DB()->writeOperateLog(QString("成功导出 %1 钱包到 %2")
                 .arg(wallet_name).arg(dest_file_path), 1);
    }
}

void OEWalletManageWidget::onBatchExportPubKey()
{
    if (!isSelectedTable()) {
        OEMessageBox::BriefMessage(this, "请选择钱包");
        return;
    }
    const QString& dest_file_path = QFileDialog::getExistingDirectory(this,
                      tr("请选择钱包导出路径"),"..");

    if (dest_file_path.isEmpty())
        return;

    const int& ROW = model_->rowCount();
    int export_count = 0;
    for (int row = 0; row < ROW; ++row) {
        if (model_->item(row)->checkState() == Qt::Checked) {
            ++export_count;
            onExportPubKey(row,dest_file_path);
        }
    }

    SRDatabase::DB()->writeOperateLog(QString("批量导出 %1 个公钥到 %2")
             .arg(export_count).arg(dest_file_path), 1);
    onUpdate();
}

void OEWalletManageWidget::onExportPubKey(int _row,
                        const QString &_exportAddr)
{
    int ret_row = tableView_->currentIndex().row();
    if (_row != -1) {
        ret_row = _row;
    }
    if (-1 == ret_row) {
        OEMessageBox::BriefMessage(this, tr("请选择要导出的钱包"));
        return;
    }

    QString wallet_path = model_->item(ret_row, WALLET_PATH)->text();
    QString wallet_config = wallet_path + "/wallet";
    QString wallet_name = model_->item(ret_row, WALLET_NAME)->text();
    static int i = 0;
    ++i;
    const QString& rwallet_name = QString::number(i) + wallet_name;

    if (!QFile(wallet_config).exists()) {
        OEMessageBox::BriefMessage(this, tr("钱包已经不存在"));
        return;
    }
    QSettings setting(wallet_config, QSettings::IniFormat);

    QString wallet_pub_key = setting.value("INFO/ek_pub_key").toString();


    // 选择导出的路径
    const QString& default_wallet_name = rwallet_name + ".seed";
    QString file_name;

    if (_exportAddr.isEmpty()) {
        file_name = QFileDialog::getSaveFileName(this,tr("选择公钥导出路径"),
                       default_wallet_name, tr("Public Seeds(*.seed)"));
    }
    else {
        file_name = _exportAddr + "/" + rwallet_name + ".seed";
    }
    // 判断是否有选择文件夹
    if (file_name.isEmpty())
        return;

    QFile file(file_name);
    if (!file.open(QIODevice::Truncate
              | QIODevice::WriteOnly)) {
        qWarning("write excel record failed,"\
               "because sign file write failed.");
        return;
    }
    QTextStream in(&file);
    in << wallet_pub_key;
    file.close();

    QString wallet_status = setting.value("INFO/status").toString();

    if (wallet_status != "提币中")
        setting.setValue("INFO/status", "使用中");

    if (_row == -1) {
        SRDatabase::DB()->writeOperateLog(QString("导出公钥(\"%1\")到 %2")
                 .arg(wallet_name).arg(file_name), 1);
        onUpdate();
    }

}

void OEWalletManageWidget::onBatchHideWallet()
{
    if (!isSelectedTable()) {
        OEMessageBox::BriefMessage(this, "请选择钱包");
        return;
    }
    const int& ROW = model_->rowCount();
    for (int row = 0; row < ROW; ++row) {
        if (model_->item(row,0)->checkState() == Qt::Checked) {
            onHideWallet(row);
        }
    }
    onUpdate();
}

void OEWalletManageWidget::onHideWallet(int _row)
{
    int ret_row = tableView_->currentIndex().row();

    if (_row != -1) {
        ret_row = _row;
    }
    if (-1 == ret_row) {
        OEMessageBox::BriefMessage(this, tr("请选择要导出的钱包"));
        return;
    }

    QString wallet_path = model_->item(ret_row, WALLET_PATH)->text();
    QString wallet_config = wallet_path + "/wallet";

    QSettings setting(wallet_config,QSettings::IniFormat);
    setting.setValue("INFO/status", "隐藏");
    if (_row == -1) {
        onUpdate();
    }
}

void OEWalletManageWidget::onNextPage(int _pageNumber)
{
    _pageNumber = _pageNumber - 1;
    if (_pageNumber < 0) {
        boxPage_->setValue(1);
        _pageNumber = 0;
    }



    onUpdate();
}

void OEWalletManageWidget::onTableClick(const QModelIndex &_index)
{
    tableView_->resizeRowToContents(_index.row());
    return;
}






bool OEWalletManageWidget::copyDir(const QString &_srcPath,
                             const QString &_destDir,
                             bool coverFileIfExist)
{
    QDir sourceDir(_srcPath);
    QDir targetDir(_destDir);
    if(!targetDir.exists()){    /**< 如果目标目录不存在，则进行创建 */
        if(!targetDir.mkdir(targetDir.absolutePath()))
            return false;
    }

    QFileInfoList fileInfoList = sourceDir.entryInfoList();
    foreach(QFileInfo fileInfo, fileInfoList){
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(fileInfo.isDir()){    /**< 当为目录时，递归的进行copy */
            if(!copyDir(fileInfo.filePath(),
                targetDir.filePath(fileInfo.fileName()),
                coverFileIfExist))
                return false;
        }
        else{            /**< 当允许覆盖操作时，将旧文件进行删除操作 */
            if(coverFileIfExist && targetDir.exists(fileInfo.fileName())){
                targetDir.remove(fileInfo.fileName());
            }

            /// 进行文件copy
            if(!QFile::copy(fileInfo.filePath(),
                targetDir.filePath(fileInfo.fileName()))){
                    return false;
            }
        }
    }
    return true;
}

void OEWalletManageWidget::onUpdate()
{
    model_->removeRows(0,model_->rowCount());
    walletInfo_->clearWallet();
    int size = walletInfo_->loadWallet(".");
    OEWalletManage::OEWalletList list = walletInfo_->getAllWallet();


    OEWalletManage::OEWalletList selected_list;

    // 获取符合展示要求的钱包
    for (int i = 0; i < list.size(); ++i) {
        auto item = list.at(i);
        if (!isWalletStatus(item.status))
            continue;
        selected_list.push_back(item);
    }

    // 计算需要展示的钱包区间
    int page_num = boxPage_->value();

    int end_num = page_num * 20;
    int begin_num = end_num - 20;
    if (begin_num < 0)
        begin_num = 0;
    if (end_num > selected_list.size())
        end_num = selected_list.size();

    // 展示钱包
    int show_count = 0;
    for (int idx = begin_num; idx < end_num; ++idx) {
        auto item = selected_list.at(idx);
        ++show_count;
        insertTableData(idx, item.name,item.status, item.author, item.crtTime, item.absPath);
    }
    if (show_count > 0) {
        tableView_->selectRow(0);
    }
    else {
        boxPage_->setValue(boxPage_->value() - 1);
    }


    labWalletCount_->setText(labWalletCount_->objectName().arg(size));
}

void OEWalletManageWidget::insertTableData(
            int _row, const QString &_walletName,
            const QString &_status,  const QString &_author,
            const QString &_crtTime, const QString &_absPath)
{
    if (_row > model_->rowCount()) {
        _row = model_->rowCount();
    }

    QStandardItem *wallet_name_item = new QStandardItem(_walletName);
    wallet_name_item->setCheckable(true);
    wallet_name_item->setCheckState(Qt::Unchecked);

    model_->setItem(_row, WALLET_NAME, wallet_name_item);
    model_->setItem(_row, WALLET_STATUS, new QStandardItem(_status));
    model_->setItem(_row, WALLET_AUTHOR, new QStandardItem(_author));
    model_->setItem(_row, WALLET_TIME, new QStandardItem(_crtTime));
    model_->setItem(_row, WALLET_PATH, new QStandardItem(_absPath));
    for (int i = 0 ; i < WALLET_COUNT; ++i) {
        model_->item(_row, i)->setTextAlignment(Qt::AlignCenter);
    }
}

void OEWalletManageWidget::showEvent(QShowEvent *event)
{
    Q_UNUSED(event);
    onUpdate();

}

bool OEWalletManageWidget::isWalletStatus(const QString &_status)
{
    int state_check = Qt::CheckState::Checked;

    if (checkNormal_->text() == _status
        && checkNormal_->checkState() == state_check) {
        return true;
    }
    if (checkBusy_->text() == _status
         && checkBusy_->checkState() == state_check) {
         return true;
    }
    if (checkHide_->text() == _status
          && checkHide_->checkState() == state_check) {
          return true;
    }
    if (checkUse_->text() == _status
           && checkUse_->checkState() == state_check) {
           return true;
    }
    return false;
}

bool OEWalletManageWidget::isSelectedTable()
{
    const int& ROW = model_->rowCount();
    for (int row = 0; row < ROW; ++row) {
        if (model_->item(row)->checkState() == Qt::Checked) {
            return true;
        }
    }
    return false;
}



